import { TextDocument, Uri } from "vscode";
import { InteractiveInputScheme, NotebookCellScheme } from "../constants";
import { isParentPath } from "../platform/fa-paths";

export function getURIFilter(
    uri: Uri,
    opts: {
        checkParent?: boolean;
        checkChild?: boolean;
    } = { checkParent: true },
): (u: Uri) => boolean {
    let uriPath = uri.path;
    while (uriPath.endsWith('/')) {
        uriPath = uriPath.slice(0, -1);
    }
    const uriRoot = `${uriPath}/`;
    function filter(candidate: Uri): boolean {
        if (candidate.scheme !== uri.scheme) {
            return false;
        }
        let candidatePath = candidate.path;
        while (candidatePath.endsWith('/')) {
            candidatePath = candidatePath.slice(0, -1);
        }
        if (opts.checkParent && isParentPath(candidatePath, uriRoot)) {
            return true;
        }
        if (opts.checkChild) {
            const candidateRoot = `${candidatePath}/`;
            if (isParentPath(uriPath, candidateRoot)) {
                return true;
            }
        }
        return false;
    }
    return filter;
}

export function noop() { }

function isUri(resource?: Uri | any): resource is Uri {
    if (!resource) {
        return false;
    }
    const uri = resource as Uri;
    return typeof uri.path === 'string' && typeof uri.scheme === 'string';
}

export function isNotebookCell(documentOrUri: TextDocument | Uri): boolean {
    const uri = isUri(documentOrUri) ? documentOrUri : documentOrUri.uri;
    return uri.scheme.includes(NotebookCellScheme) || uri.scheme.includes(InteractiveInputScheme);
}